﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Migrations;
using System.Data.Entity;

namespace BlogModel.DAL
{
    public class CommentDB
    {
        private static readonly BlogModelContainer _context = new BlogModelContainer();

        public static BlogModelContainer Context
        {
            get { return _context; }
        }

        private static readonly DbSet<Comment> _comments = Context.CommentSet;

        public static DbSet<Comment> Comments
        {
            get { return _comments; }
        }

        public static int Save()
        {
            try
            {
                return Context.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                            validationErrors.Entry.Entity.ToString(),
                            validationError.ErrorMessage);
                        // raise a new exception nesting
                        // the current instance as InnerException
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }
        }

        public static List<Comment> PrintCommentsOnPostId(int postId)  //Klar! Testad och OK!
        {
            return Context.CommentSet
                .Where(c => c.PostId == postId && !c.IsDeleted).ToList();
        }
    }
}
